package com.mk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mk.dto.PageDTO;
import com.mk.entity.Pet;
import com.mk.mapper.PetMapper;
import com.mk.query.PetQuery;
import com.mk.service.IPetService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class PetServiceImpl extends ServiceImpl<PetMapper, Pet> implements IPetService {

    private final PetMapper petMapper;

    /**
     * 添加宠物信息
     * @param pet
     */
    @Override
    public void add(Pet pet) {
        pet.setCreateTime(LocalDateTime.now());
        pet.setUpdateTime(LocalDateTime.now());
        pet.setScoreTime(LocalDateTime.now());
        petMapper.save(pet);
        Long id = pet.getId();
        pet.setPetNumber("K9CC" + String.format("%05d", id));
        petMapper.update(new LambdaUpdateWrapper<Pet>()
                .set(Pet::getPetNumber, pet.getPetNumber())
                .eq(Pet::getId, id));
    }

    /**
     * 获取宠物信息
     * @param numberPlate
     * @return
     */
    @Override
    public Pet getByNumberPlate(String numberPlate) {
        return petMapper.selectOne(new LambdaQueryWrapper<Pet>().eq(Pet::getNumberPlate, numberPlate).select());
    }

    /**
     * 学法减分
     * @param petId
     * @param score
     */
    @Override
    public void deductPoints(Long petId, Integer score) {
        Pet pet = petMapper.selectById(petId);
        Integer resultScore = pet.getScore() - score;
        if (resultScore < 0) resultScore = 0;
        LambdaUpdateWrapper<Pet> wrapper = new LambdaUpdateWrapper<Pet>()
                .set(Pet::getScore, resultScore)
                .set(Pet::getUpdateTime, LocalDateTime.now())
                .eq(Pet::getId, petId);
        petMapper.update(wrapper);
    }

    /**
     * 客户端分页查询
     * @param query
     * @return
     */
    //TODO 根据UI进行修改
    @Override
    public PageDTO<Pet> queryPetsPage(PetQuery query) {
        String name = query.getName();
        String status = query.getStatus();
        Integer score = query.getScore();
        //1.构建查询条件
        Page<Pet> page = query.toMpPageDefaultSortByUpdateTimeDesc();

        //2.分页查询
        lambdaQuery()
                .like(name != null, Pet::getName, name)
                .eq(status != null, Pet::getStatus, status);

        return null;
    }
}
